import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import Logger from '../log'
import { transAxiosInfo } from '@/utils/translator'
import { alertModal } from '@/components/Modal'
import { getErrorCodeMsg } from './errorCode'
import { currentHost } from '@/utils/baseVariable'
// import qs from 'qs'

const prefix = '/'
// const prefix = '/smcapi'

function handleErrorCode(response: AxiosResponse<any>) {
	const { data } = response
	if (
		data &&
		data.errorCode &&
		(data.errorCode === 100013 ||
			data.errorCode === 100012 ||
			data.errorCode === 100011 ||
			data.errorCode === 100010)
	) {
		window.location.href = window.location.origin + '/portal/login'

		return 'error'
	}
}

export function setToken(fn: (token: string) => void) {
	if (window.KDV_BP_KEY) {
		fn(window.KDV_BP_KEY)
	} else {
		const script = document.createElement('script')
		script.src = '/web/kdv/biz/bp.min.js?t=' + new Date().getTime()
		script.onload = function () {
			fn(window.KDV_BP_KEY)
		}
		//@ts-ignore  ie才会使用
		script.onreadystatechange = function () {
			//@ts-ignore
			if (script.readyState === 'loaded' || script.readyState === 'complete') {
				fn(window.KDV_BP_KEY)
			}
		}
		document.body.appendChild(script)
	}
}

function setRequestLog(config: AxiosRequestConfig<any>) {
	Logger.add({
		info: {
			url: config.url,
			data: unescape(config.data),
			params: unescape(JSON.stringify(config.params)),
			type: config.method?.toUpperCase(),
		},
		type: `request-${config.method?.toUpperCase() || 'UNKNOW'}`,
	})
}
function setResponseLog(response: AxiosResponse<any, any>) {
	Logger.add({
		info: {
			url: response.config.url,
			data: response.request.responseText,
			type: response.config.method?.toUpperCase(),
			status: response.status,
		},
		type: `response-${response.config.method?.toUpperCase() || 'UNKNOW'}`,
	})
}

const fetchAxios = axios.create({
	baseURL: prefix,
	timeout: 115000,
})

//请求拦截
fetchAxios.interceptors.request.use(
	(config) => {
		config.headers = config.headers || {}
		config.headers['Mo-Source'] = window.MoSource
		if (config.method === 'post' || config.method === 'put' || config.method === 'delete') {
			return new Promise(function (resolve) {
				setToken((KDV_BP_KEY) => {
					config.headers = config.headers || {}
					config.headers['X-CSRF-TOKEN'] = KDV_BP_KEY
					setRequestLog(config)
					resolve(config)
				})
			})
		}
		setRequestLog(config)
		return config
	},
	(error) => {
		return Promise.reject(error)
	}
)
let count = 0 //用来解决同时多个接口请求错误时 弹出多个提示的问题
const initCount = () => {
	count = 0
}
function HTMLDecode(text: string): string {
	if (text && typeof text === 'string') {
		text = text
			.replace(new RegExp('&amp;', 'gm'), '&')
			.replace(new RegExp('&lt;', 'gm'), '<')
			.replace(new RegExp('&gt;', 'gm'), '>')
			.replace(new RegExp('&#39;', 'gm'), "'")
			.replace(new RegExp('&#x27;', 'gm'), "'")
			.replace(new RegExp('&quot;', 'gm'), '"')
	}
	return text
}
//返回拦截
fetchAxios.interceptors.response.use(
	(response) => {
		// 通过返回的success判断接口返回成功
		let decdata = {
			data: null,
			description: '',
			error_code: 0,
			success: 0,
		}
		try {
			let strData = HTMLDecode(JSON.stringify(response.data))
			decdata = JSON.parse(strData)
		} catch (e) {
			console.error(e)
		}
		let data = transAxiosInfo(decdata) as AxiosResponse<any, any>  

		const code = data.errorCode
		const success = data.success
		setResponseLog(response)
		if (success === 1) {
			return Promise.resolve(data)
		} else {
			let config = response.config

			//接口中不传isShowTip，默认是常规的处理:在接口失败失败后，已弹窗形式提示失败原因
			if (code === 100010 || code === 100011 || code === 100012 || code === 100013 || code === 200001) {
				window.location.href = '/portal/login'
				return Promise.reject(data)
			}
			// 框架约束的所致 99993 为正常返回
			if (code === 99993) {
				return Promise.resolve(data)
			}
			if (config.isShowTip !== false) {
				let msg = ''
				let description = data.description || ''
				if (code === 52004 || code === 131002) {
					msg = description ? description : getErrorCodeMsg(code, description)
				} else {
					msg = getErrorCodeMsg(code, description)
				}
				if (msg) {
					if (count === 0) {
						alertModal({
							msg: msg,
							onOk: initCount,
							onCancel: initCount,
						})
						count = 1
					}
				}
			}

			return Promise.reject(data)
		}
		// if (handleErrorCode(response) === 'error') {
		// 	return Promise.reject('error: go login page by errorCode')
		// }

		// if (response.status !== 200) {
		// 	return Promise.reject('error: response status is not 200')
		// } else {
		// 	return response
		// }
	},
	(error) => {
		if (error && error.response) {
			handleErrorCode(error.response)
		}
		return Promise.reject(error)
	}
)

export default fetchAxios
